package example.fileupload;

import com.google.protobuf.ByteString;
import grpc.htsoft.fileupload.File;
import grpc.htsoft.fileupload.FileServiceGrpc;
import grpc.htsoft.fileupload.FileUploadRequest;
import grpc.htsoft.fileupload.MetaData;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class fileclient {

    public static void main(String[] argc) throws IOException {
        System.out.println("Hello, FileClient!");
         ManagedChannel channel;
         FileServiceGrpc.FileServiceStub fileServiceStub;
        channel = ManagedChannelBuilder.forAddress("localhost", 50096)
                .usePlaintext()
                .build();
        fileServiceStub = FileServiceGrpc.newStub(channel);

//        FileUploadObserver fileUploadObserver = new FileUploadObserver();
//        fileServiceStub.upload(fileUploadObserver);

        StreamObserver<FileUploadRequest> streamObserver = fileServiceStub.upload(new FileUploadObserver());

// input file for testing
        Path path = Paths.get("/Users/zgw/Pictures/vlcsnap-2020-07-29-10h36m29s719.png");

// build metadata
        FileUploadRequest metadata = FileUploadRequest.newBuilder()
                .setMetadata(MetaData.newBuilder()
                        .setName("output")
                        .setType("png").build())
                .build();
        streamObserver.onNext(metadata);

// upload file as chunk
        InputStream inputStream = Files.newInputStream(path);
        byte[] bytes = new byte[4096];
        int size;
        while ((size = inputStream.read(bytes)) > 0){
            System.out.println("file content: " + size);
            FileUploadRequest uploadRequest = FileUploadRequest.newBuilder()
                    .setFile(File.newBuilder().setContent(ByteString.copyFrom(bytes, 0 , size)).build())
                    .build();
            streamObserver.onNext(uploadRequest);
        }

// close the stream
        inputStream.close();
        streamObserver.onCompleted();
        System.out.println("file content completed!");
    }
}
